package cn.itcast.tanhua.server.interceptor;

import cn.itcast.tanhua.common.pojo.User;
import cn.itcast.tanhua.common.utils.NoAuthorization;
import cn.itcast.tanhua.common.utils.UserThreadLocal;
import cn.itcast.tanhua.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName UserTokenInterceptor
 * @Description token验证拦截器，仅拦截当前工程的所有请求
 * @Author WU
 * @Date 2021/5/30 19:00
 * @Version 1.0
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

//        从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
//            如果token不为空则验证token
            User user = this.userService.queryUserByToken(token);
//            如果user不为空，则放入ThreadLocal
            if (null != user) {
                UserThreadLocal.set(user);
                return true;
            }
        }

//        token为空或者获取到的user对象为空，token无效，则响应状态401
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        token验证完成后从ThreadLocal中移除user，防止内存泄露
        UserThreadLocal.remove();
    }
}
